<?php

namespace app\api\controller;
use think\Db;
class Login extends Base {
    public function getUserStatus($phone)
    {
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if ($username['user_status'] == 0) {
            return array('status' => 110, 'msg' => '账号还在审核中，请耐心等待','user'=>$username);
        } else if ($username['user_status'] == 2) {
            return array('status' => 111, 'msg' => '审核未通过','user'=>$username);
        } else if ($username['user_status'] == 1) {
            return array('status' => 200, 'msg' => 'ok');
        } else {
            return array('status' => 100, 'msg' => '账号冻结');
        }
    }
    /**
     * 账号密码登录
     * @return bool
     * 参数：账号、密码
     * 返回值：0参数错误，1手机号码错误，2密码格式错误，3没有此用户，4密码错误，5成功
     */
    public  function userLogin(){
//        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['pass'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $pass = $_POST['pass'];
        if(preg_match("/^1[3456789]\d{9}$/", $phone)){
            if(empty($pass) || !isset($pass)){
                return json_encode(['status'=>2,'msg'=>'请填写正确的密码']);
            }else{
                $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
                if(empty($username)){
                    return json_encode(['status'=>3,'msg'=>'该手机号未注册，无法登录']);
                }else{
                    if($username['user_password'] != md5($pass)){
                        return json_encode(['status'=>4,'msg'=>'密码错误']);
                    }else{
                        $userStatus = $this->getUserStatus($phone);
                        if($userStatus['status'] != 200){
                            return json_encode($userStatus);
                        }else{
                            //更新token
                            $token = md5(date('YmdHis') . rand(100000,999999));
                            Db::table('up_u_user')->where('user_phone',$phone)
                                ->update(['user_token'=>$token]);
                            $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
                            return json_encode(['status'=>200,'msg'=>$username]);
                        }
                    }
                }
            }
        }else{
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
    }

    /**
     * 手机登录或注册时发送的验证码
     * @return bool
     * 参数：phone type(1是手机登录 2是注册和更换手机号 3是忘记密码和修改密码，4是修改支付密码)
     * 返回值：0参数错误，1手机格式错误，21登录无此号，22注册有此号，3验证码发送失败，4返回md5加密验证码
     */
    public  function getPhoneCode(){
//        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['type'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $num = rand(100000,999999);
        $phone = $_POST['phone'];
        $type = $_POST['type'];
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();

            if(empty($username) && $type==1){
                return json_encode(['status'=>404,'msg'=>'没有此手机号码用户']);
            }
            if(empty($username) && $type==3){
                return json_encode(['status'=>21,'msg'=>'没有此手机号码用户']);
            }
            if(!empty($username) && $type==2){
                return json_encode(['status'=>22,'msg'=>'已经有此手机号码用户']);
            }
            if(empty($username) && $type==4){
                return json_encode(['status'=>22,'msg'=>'没有此手机号码用户']);
            }

        //判断审核情况start
        if($type == 3 || $type == 1){
            $userStatus = $this->getUserStatus($phone);
            if($userStatus['status'] != 200){
                return json_encode($userStatus);
            }
        }
        //判断审核情况end
        $sendres = $this->duaxin($phone,$num);
        if($sendres['code'] != '00000'){
            return json_encode(['status'=>3,'msg'=>'短信平台错误：'.$sendres['msg']]);
        }else {
            //=============================
            $isset = Db::table('up_phonecode')->where('phone', $phone)->find();
            if ($isset) {
                $res = Db::table('up_phonecode')->where('phone', $phone)->update(['code' => md5($num), 'time2' => time(), 'status' => 0]);
            } else {
                $res = Db::table('up_phonecode')->insert(['phone' => $phone, 'code' => md5($num), 'time2' => time()]);
            }
            if (!$res) {
                return json_encode(['status' => 31, 'msg' => '数据库操作失败']);
            }
            //===============================================
            return json_encode(['status' => 200, 'msg' => md5($num)]);
        }
    }

    /**
     * 手机登录
     * @return bool
     * 参数：phone,code，newpass
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，200成功
     */

    public  function phoneLogin(){
//        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['code'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $code = $_POST['code'];
        $userStatus = $this->getUserStatus($phone);
        if($userStatus['status'] != 200){
            return json_encode($userStatus);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        if($code == ''){
            return json_encode(['status'=>2,'msg'=>'有未填项']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username)){
            return json_encode(['status'=>404,'msg'=>'没有此手机号码用户']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 3601){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
//        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
//        if(empty($username)){
//            return json_encode(['status'=>404,'msg'=>'没有此手机号码用户']);
//        }
        $token = md5(date('YmdHis').rand(100000,999999));
        $res = Db::table('up_u_user')->where('user_phone',$phone)->update(['user_token'=>$token]);
        if($res){
            Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
            $user = Db::table('up_u_user')->where('user_phone',$phone)->find();
            return json_encode(['status'=>200,'msg'=>$user]);
        }else{
            return json_encode(['status'=>3,'msg'=>'密码重置失败']);
        }
    }

    /**
     * 用户注册第一步
     * @return bool
     */

    public  function userRegOne(){
//        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['code'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $code = $_POST['code'];
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        if($code == ''){
            return json_encode(['status'=>2,'msg'=>'有未填项']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if($username){
            return json_encode(['status'=>3,'msg'=>'有此手机号码用户']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 3601){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        return json_encode(['status'=>200,'msg'=>'ok']);
    }
    /**
     * 用户注册第二步
     * @return bool
     */

    public  function userRegTwo(){
        extract(input());
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $have = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if($have){
            return json_encode(['status'=>3,'msg'=>'有此手机号码用户']);
        }
        $data = array();
        $data['user_phone'] = $phone;
        $data['user_password'] = md5($pass);
        $data['user_shopname'] = $shopname;
        $data['user_username'] = $username;
        $data['user_idcard'] = $idcard;
        $data['user_sheng'] = $sheng;
        $data['user_shi'] = $shi;
        $data['user_qu'] = $qu;
        $data['user_ssq_str'] = $ssqstr;
        $data['user_address'] = $address;
        $data['user_idcard_img'] = $idcard_img;
        $data['user_zhizhao'] = $zhizhao_img;
        $data['user_type'] = $type;
        $data['user_time'] = date('Y-m-d H:i:s');
        $data['user_update_time'] = date('Y-m-d H:i:s');
        if($type == 2){
            $data['user_zizhi'] = $zizhi_img;
            $data['user_pinpai_id'] = $user_pinpai;
        }
        $token = md5(date('YmdHis').rand(100000,999999));
        $data['user_token'] = $token;
        $res = Db::table('up_u_user')->insert($data);
        if($res){
            Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
            return json_encode(['status'=>200,'msg'=>'提交成功，请等待审核']);
        }else{
            return json_encode(['status'=>3,'msg'=>'提交失败']);
        }
    }
    /**
     * 忘记密码
     * @return bool
     * 参数：phone,code，newpass
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，200成功
     */

    public  function forgetPass(){
//        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['code'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $code = $_POST['code'];
        $new = $_POST['newpass'];
        $new2 = $_POST['surepass'];
        $userStatus = $this->getUserStatus($phone);
        if($userStatus['status'] != 200){
            return json_encode($userStatus);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        if($new != $new2){
            return json_encode(['status'=>1,'msg'=>'密码输入不一致']);
        }
        if($code == ''){
            return json_encode(['status'=>2,'msg'=>'有未填项']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username)){
            return json_encode(['status'=>3,'msg'=>'没有此手机号码用户']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 3601){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        $token = md5(date('YmdHis').rand(100000,999999));
        $res = Db::table('up_u_user')->where('user_phone',$phone)->update(['user_password'=>md5($new),'user_token'=>$token]);
        if($res){
            Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
            $user = Db::table('up_u_user')->where('user_phone',$phone)->find();
            return json_encode(['status'=>200,'msg'=>$user]);
        }else{
            return json_encode(['status'=>3,'msg'=>'密码重置失败']);
        }
    }
    /**
     * 修改支付密码
     * @return bool
     * 参数：phone,code，newpass
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，200成功
     */

    public  function updatePayPass(){
//        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['code'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $code = $_POST['code'];
        $new = $_POST['newpass'];
        $new2 = $_POST['surepass'];
        if($new != $new2){
            return json_encode(['status'=>1,'msg'=>'密码输入不一致']);
        }
        if($code == ''){
            return json_encode(['status'=>2,'msg'=>'有未填项']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($username)){
            return json_encode(['status'=>3,'msg'=>'没有此手机号码用户']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$phone)->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 3601){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        $res = Db::table('up_u_user')->where('user_phone',$phone)->update(['user_pay_pass'=>md5($new)]);
        if($res){
            Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
            $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
            return json_encode(['status'=>200,'msg'=>$username]);
        }else{
            return json_encode(['status'=>3,'msg'=>'修改失败或未做任何修改']);
        }
    }
    /**
     * 更换手机号
     * @return bool
     * 参数：phone,code，newpass
     * 返回：0参数错误，1手机格式错误，21验证码错误，22验证码超时，3无此用户，200成功
     */

    public  function updateMyPhone(){
//        header("Access-Control-Allow-Origin:*");
        if(!isset($_POST['phone']) || !isset($_POST['code'])){
            return json_encode(['status'=>0,'msg'=>'参数错误']);
        }
        $phone = $_POST['phone'];
        $code = $_POST['code'];
        $new = $_POST['newphone'];
        if($code == ''){
            return json_encode(['status'=>2,'msg'=>'有未填项']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$new)->find();
        if($username){
            return json_encode(['status'=>3,'msg'=>'有此手机号码用户']);
        }
        //=============================================
        $res = Db::table('up_phonecode')->where('phone',$new)->find();
        //=============================================================
        if($code != $res['code']){
            return json_encode(['status'=>21,'msg'=>'验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 3601){
            return json_encode(['status'=>22,'msg'=>'验证码超时']);
        }
        if($res['status']==1){
            return json_encode(['status'=>23,'msg'=>'验证码已使用']);
        }
        $res = Db::table('up_u_user')->where('user_phone',$phone)->update(['user_phone'=>$new]);
        if($res){
            Db::table('up_phonecode')->where('phone',$new)->update(['status'=>1]);
            $user = Db::table('up_u_user')->where('user_phone',$new)->find();
            return json_encode(['status'=>200,'msg'=>$user]);
        }else{
            return json_encode(['status'=>3,'msg'=>'更换失败']);
        }
    }


    /**
     * 拒绝以后可以修改自己的资料
     * @return bool
     */

    public  function userUpdateResfuse(){
        extract(input());
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json_encode(['status'=>1,'msg'=>'请填写正确的手机号码']);
        }
        $have = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(!$have){
            return json_encode(['status'=>3,'msg'=>'没有此手机号码用户']);
        }
        $data = array();
        $data['user_shopname'] = $shopname;
        $data['user_username'] = $username;
        $data['user_idcard'] = $idcard;
        $data['user_sheng'] = $sheng;
        $data['user_shi'] = $shi;
        $data['user_qu'] = $qu;
        $data['user_ssq_str'] = $ssqstr;
        $data['user_address'] = $address;
        $data['user_idcard_img'] = $idcard_img;
        $data['user_zhizhao'] = $zhizhao_img;
        $data['user_type'] = $type;
        $data['user_time'] = date('Y-m-d H:i:s');
        $data['user_update_time'] = date('Y-m-d H:i:s');
        $data['user_status'] = 0;
        if($type == 2){
            $data['user_zizhi'] = $zizhi_img;
            $data['user_pinpai_id'] = $user_pinpai;
        }
        $res = Db::table('up_u_user')->where('user_phone',$phone)->update($data);
        if($res){
            Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
            return json_encode(['status'=>200,'msg'=>'提交成功，请等待审核']);
        }else{
            return json_encode(['status'=>3,'msg'=>'提交失败']);
        }
    }
    /**
     * 关于我们和注册协议
     */
    public function regAndAbout (){
        extract(input());
        $data = Db::table('up_about')
            ->where('a_id',$type)
            ->find();
        return json_encode(['status'=>200,'msg'=>$data]);
    }

    /**
     * location 自动定位返回id
     * $location  地区名称
     */
    public function location (){
        extract(input());
        $res = array();
        if(isset($sheng)){
            $shengID = Db::table('up_area')
                ->where('district',$sheng)
                ->value('district_id');
            $res['sheng'] = $shengID;
        }
        if(isset($shi)){
            $shiID = Db::table('up_area')
                ->where('district',$shi)
                ->value('district_id');
            $res['shi'] = $shiID;
        }
        if(isset($qu)){
            $quID = Db::table('up_area')
                ->where('district',$qu)
                ->value('district_id');
            $res['qu'] = $quID;
        }
        return json_encode(['status'=>200,'msg'=>$res]);
    }
    /**
     * 生成省市区json数据：makeJson
     * @return string
     */
    public function makeJson()
    {
//        header("Content-type: text/html; charset=utf-8");
        $pro = Db::table('up_area')
            ->where('pid',1)
            ->field('district_id id,district name')
            ->select();
        foreach($pro as $k=>$v){
            $pro[$k]['parentId'] = 0;
            $city = Db::table('up_area')
                ->where('pid',$v['id'])
                ->where('level',2)
                ->field('district_id id,district name,pid parentId')
                ->select();
            foreach ($city as $kk=>$vv){
                $city[$kk]['sub'] = Db::table('up_area')
                    ->where('pid',$vv['id'])
                    ->where('level',3)
                    ->field('district_id id,district name,pid parentId')
                    ->select();
            }
            $pro[$k]['sub'] = $city;

        }
//        $pro_json = json_encode($pro);
//        return json_encode(['status'=>200,'msg'=>$pro_json]);
        return json_encode($pro);
    }
    /**
     * 获取所有城市
     * @return string
     */
    public function getCitys(){
        $res = Db::table('up_area')
            ->where('level',2)
            ->field('district_id id,district city')
            ->select();
        return json_encode(['status'=>200,'msg'=>$res]);
    }
    /*====自动定位End=====*/

    //***********************个人资料及修改************************
    /**
     * uploadLocality图片上传至本地&压缩
     */
    public function uploadImage(){
        $tmp = $_FILES['image']['tmp_name'];
        $size = $_FILES['image']['size'];
        if($size > 1024*1024*5){
            return json_encode(['status'=>0,'msg'=>"图片不得超过5M！"]);
        }
        $today = date('Ymd');
        $dir = $_SERVER['DOCUMENT_ROOT'] . '/uploads/images/' . $today;
        if(!file_exists($dir)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($dir, 0700,true);
        }
//        $url =  "http://".$_SERVER['HTTP_HOST'];
        if($tmp){
            //=======重命名=====
            $rand = date('YmdHis').rand(100000,999999);
            $newName = $rand . '.png';
            //=======================
            if(move_uploaded_file($tmp,"{$dir}/{$newName}")){
                $imgUrl = "/uploads/images/$today/$newName";
                if($size > 1024*1024*2){
                    $this->image_png_size_add("{$dir}/{$newName}","{$dir}/{$newName}");
                }
                return json_encode(['status'=>200,'msg'=>$imgUrl]);
            }else{
                return json_encode(['status'=>0,'msg'=>'图片保存失败']);
            }
        }else{
            return json_encode(['status'=>0,'msg'=>"上传一张图！"]);
        }
    }

    public function test(){
        $aa = array('今天','明天');
        $bb = array('00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23');
        $cc = array('00','15','30','45');
        foreach ($aa as $k=>$v){
            $a[$k]['district'] = $v;
            $a[$k]['district_id'] = $k+1;
            foreach ($bb as $k2=>$v2){
                $b[$k2]['district'] = $v2;
                $b[$k2]['district_id'] = $k2;
                foreach ($cc as $k3=>$v3){
                    $c[$k3]['district'] = $v3;
                    $c[$k3]['district_id'] = $k3;
                }
                $b[$k2]['subDistrict'] = $c;
            }
            $a[$k]['subDistrict'] = $b;
        }
		$a[2]['district'] = '立即预约';
        $a[2]['district_id'] = 0;
        $aaa = json_encode($a);
        echo $aaa;
    }
    
    /**
     * @return \think\response\Json
     * 选择品牌
     */
    public function chooseBrand(){
        $brandList = Db::table('up_pinpai')->field('p_id, p_name')->select();
        if($brandList){
            return json(['status' => 200, 'msg' => $brandList]);
        }else{
            return json(['status' => 0, 'msg' => []]);
        }
    }
}